/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.cms.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.server.common.config.Global;
import com.server.common.utils.StringUtils;
import com.server.modules.api.service.IBaseJPushService;
import com.server.modules.api.service.IJPushService;
import com.server.modules.api.service.IMService;
import com.server.modules.cms.entity.Article;
import com.server.modules.cms.entity.Category;
import com.server.modules.cms.entity.Site;
import com.server.modules.cms.utils.CmsUtils;
import com.server.modules.cms.utils.TplUtils;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.article.ArticlePush;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.service.SystemService;
import com.server.modules.sys.service.article.ArticlePushService;
import com.server.modules.sys.service.member.MemberService;
import com.server.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.server.common.mapper.JsonMapper;
import com.server.common.persistence.Page;
import com.server.common.web.BaseController;
import com.server.modules.cms.service.ArticleDataService;
import com.server.modules.cms.service.ArticleService;
import com.server.modules.cms.service.CategoryService;
import com.server.modules.cms.service.FileTplService;
import com.server.modules.cms.service.SiteService;

/**
 * 文章Controller
 * @author ThinkGem
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = "${adminPath}/cms/article")
public class ArticleController extends BaseController {

	
	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticlePushService articlePushService;
	@Autowired
	private ArticleDataService articleDataService;
	@Autowired
	private CategoryService categoryService;
    @Autowired
   	private FileTplService fileTplService;
    @Autowired
   	private SiteService siteService;

	@Autowired
	private IMService imService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private MemberService memberService;

	@Autowired
	private IJPushService jPushService;
	
	@ModelAttribute
	public Article get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return articleService.get(id);
		}else{
			return new Article();
		}
	}
	
	@RequiresPermissions("cms:article:view")
	@RequestMapping(value = {"list", ""})
	public String list(Article article, HttpServletRequest request, HttpServletResponse response, Model model) {
//		for (int i=0; i<10000000; i++){
//			Article a = new Article();
//			a.setCategory(new Category(article.getCategory().getId()));
//			a.setTitle("测试测试测试测试测试测试测试测试"+a.getCategory().getId());
//			a.setArticleData(new ArticleData());
//			a.getArticleData().setContent(a.getTitle());
//			articleService.save(a);
//		}
        Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, true); 
        model.addAttribute("page", page);
		return "modules/cms/articleList";
	}

	@RequiresPermissions("cms:article:view")
	@RequestMapping(value = "form")
	public String form(Article article, Model model) {
		// 如果当前传参有子节点，则选择取消传参选择
		if (article.getCategory()!=null && StringUtils.isNotBlank(article.getCategory().getId())){
			List<Category> list = categoryService.findByParentId(article.getCategory().getId(), Site.getCurrentSiteId());
			if (list.size() > 0){
				article.setCategory(null);
			}else{
				article.setCategory(categoryService.get(article.getCategory().getId()));
			}
		}
		article.setArticleData(articleDataService.get(article.getId()));
//		if (article.getCategory()=null && StringUtils.isNotBlank(article.getCategory().getId())){
//			Category category = categoryService.get(article.getCategory().getId());
//		}
        model.addAttribute("contentViewList",getTplContent());
        model.addAttribute("article_DEFAULT_TEMPLATE",Article.DEFAULT_TEMPLATE);
		model.addAttribute("article", article);
		CmsUtils.addViewConfigAttribute(model, article.getCategory());
		return "modules/cms/articleForm";
	}

	@RequiresPermissions("cms:article:edit")
	@RequestMapping(value = "save")
	public String save(Article article, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, article)){
			return form(article, model);
		}
		articleService.save(article);
		addMessage(redirectAttributes, "保存文章'" + StringUtils.abbr(article.getTitle(),50) + "'成功");
		String categoryId = article.getCategory()!=null?article.getCategory().getId():null;
		return "redirect:" + adminPath + "/cms/article/?repage&category.id="+(categoryId!=null?categoryId:"");
	}
	
	@RequiresPermissions("cms:article:edit")
	@RequestMapping(value = "delete")
	public String delete(Article article, String categoryId, @RequestParam(required=false) Boolean isRe, RedirectAttributes redirectAttributes) {
		// 如果没有审核权限，则不允许删除或发布。
		if (!UserUtils.getSubject().isPermitted("cms:article:audit")){
			addMessage(redirectAttributes, "你没有删除或发布权限");
		}
		articleService.delete(article, isRe);
		addMessage(redirectAttributes, (isRe!=null&&isRe?"发布":"删除")+"文章成功");
		return "redirect:" + adminPath + "/cms/article/?repage&category.id="+(categoryId!=null?categoryId:"");
	}

	/**
	 * 文章选择列表
	 */
	@RequiresPermissions("cms:article:view")
	@RequestMapping(value = "selectList")
	public String selectList(Article article, HttpServletRequest request, HttpServletResponse response, Model model) {
        list(article, request, response, model);
		return "modules/cms/articleSelectList";
	}
	
	/**
	 * 通过编号获取文章标题
	 */
	@RequiresPermissions("cms:article:view")
	@ResponseBody
	@RequestMapping(value = "findByIds")
	public String findByIds(String ids) {
		List<Object[]> list = articleService.findByIds(ids);
		return JsonMapper.nonDefaultMapper().toJson(list);
	}

	/**
	 * 通过文章id把文章推送给手机
	 */
	@RequiresPermissions("cms:article:view")
    @ResponseBody
    @RequestMapping(value = "pushArticleToApp")
    public Object pushArticleToApp(Article article,HttpServletRequest request) {
        Map<String,String> ext=new HashMap();
        List<String> target=new ArrayList<>();
        User user = UserUtils.getUser();
        List<Member> list = memberService.findList(new Member());
        for (Member m:list) {
            target.add(m.getHxUsername());
        }
        String path = request.getContextPath();
        String adminPath=Global.getAdminPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+adminPath+path+"/";
        String link=basePath+"cms/article/detailPage?id="+article.getId();
        ext.put("type","3");//类型3：资讯link类型
        ext.put("title",article.getTitle());//资讯title
       // ext.put("description",article.getDescription());//资讯摘要
      //  ext.put("image",article.getImage());//资讯缩略图（没设置的话app端最好给个默认的并设置下大小）
        ext.put("link",link);//资讯链接
		ArticlePush articlePush=new ArticlePush();
		articlePush.setArticleId(article.getId());
		articlePush.setLink(link);
		articlePushService.save(articlePush);
		jPushService.pushAll("资讯推荐："+article.getTitle(),ext);
     //   imService.sendMessages("users", target,  msg, "客服经理", ext);
        return ext;
    }
    @RequestMapping(value = "detailPage")
    public String detailPage(Article article,HttpServletRequest request,Model model) {
        // 如果当前传参有子节点，则选择取消传参选择
        if (article.getCategory()!=null && StringUtils.isNotBlank(article.getCategory().getId())){
            List<Category> list = categoryService.findByParentId(article.getCategory().getId(), Site.getCurrentSiteId());
            if (list.size() > 0){
                article.setCategory(null);
            }else{
                article.setCategory(categoryService.get(article.getCategory().getId()));
            }
        }
        article.setArticleData(articleDataService.get(article.getId()));
//		if (article.getCategory()=null && StringUtils.isNotBlank(article.getCategory().getId())){
//			Category category = categoryService.get(article.getCategory().getId());
//		}
		// 文章阅读次数+1
		articleService.updateHitsAddOne(article.getId());
        model.addAttribute("contentViewList",getTplContent());
        model.addAttribute("article_DEFAULT_TEMPLATE",Article.DEFAULT_TEMPLATE);
        model.addAttribute("article", article);
        return "modules/cms/articleDetail";
    }

    private List<String> getTplContent() {
   		List<String> tplList = fileTplService.getNameListByPrefix(siteService.get(Site.getCurrentSiteId()).getSolutionPath());
   		tplList = TplUtils.tplTrim(tplList, Article.DEFAULT_TEMPLATE, "");
   		return tplList;
   	}
}
